package org.jawa.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jawa.ApplicationState;
import org.jawa.Constants;

/**
 * 根据当然系统的运行状态，控制系统页面的访问
 * 
 * @author NAN
 * 
 */
public class ApplicationStateFilter implements Filter {
	private String setupPage;
	private static final String SETUP_PAGE_DEFAULT = "/setup/index.jsp";

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		ApplicationState applicationState = Constants.getApplicationState();

		String requestURI = request.getRequestURI();

		if (ApplicationState.SETUP == applicationState) {
			// 如果当前处于安装状态，不可以访问除安装外的其它页面
			if (requestURI.contains("/setup/")
					|| requestURI.contains("/scripts/")
					|| requestURI.contains("/resources/")
					|| requestURI.contains("/dwr/")
					|| requestURI.contains("/images")
					|| requestURI.contains("/styles")) {
				chain.doFilter(req, res);
				return;
			} else {
				dispatch(request, response, setupPage);
				return;
			}

		}

		if (applicationState == ApplicationState.RUNNING) {
			// 如果当前处于正常运行状态，不可以访问安装页面
			if (requestURI.contains("/setup")) {
				dispatch(request, response, "/index.jsp");
				return;
			} else {
				chain.doFilter(req, res);
				return;
			}
		}
		
		if (applicationState == ApplicationState.RESTART) {
			// 如果当前处于必须重启状态，不可以访问任何页面
			if (!requestURI.contains("/restart-required.jsp")) {
				dispatch(request, response, "/nodecorate/restart-required.jsp");
				return;
			} else {
				chain.doFilter(req, res);
				return;
			}
		}

		chain.doFilter(req, res);
	}

	public void destroy() {
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		try {
			setupPage = filterConfig.getInitParameter("SETUP_PAGE");
			if (null == setupPage)
				setupPage = "/setup/index.jsp";
		} catch (Exception ex) {
			setupPage = "/setup/index.jsp";
		}
	}

	private void dispatch(HttpServletRequest request,
			HttpServletResponse response, String resource) throws IOException,
			ServletException {
		if (null == resource)
			throw new NullPointerException("Dispatch resource is null.");
		if (resource.startsWith("http://") || resource.startsWith("https://")) {
			response.sendRedirect(resource);
			return;
		}
		if (resource.contains(request.getContextPath()))
			response.sendRedirect(resource);
		else
			response.sendRedirect((new StringBuilder()).append(
					request.getContextPath()).append(resource).toString());
	}

}
